<template>
  <div class="container">
    <el-tabs v-model="activeTab">
      <el-tab-pane label="用户信息" name="userInfo">
        <el-row justify="center" :gutter="20">
          <el-col :span="16">
            <el-card class="content-card" shadow="always">
              <h2 style="margin-top: 0">用户信息</h2>
              <el-form :model="userInfo" label-width="100px" :rules="userRules" ref="userForm">
                <el-form-item label="用户名" prop="username">
                  <el-input v-model="userInfo.username"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                  <el-input v-model="userInfo.email"></el-input>
                </el-form-item>
                <el-form-item label="电话号码">
                  <el-input v-model="userInfo.phoneNumber" disabled></el-input>
                </el-form-item>
                <el-form-item label="创建时间">
                  <el-input :value="formatDate(userInfo.createdAt)" disabled></el-input>
                </el-form-item>
                <el-form-item label="更新时间">
                  <el-input :value="formatDate(userInfo.updatedAt)" disabled></el-input>
                </el-form-item>
                <div class="mb-2 ml-4">
                  <el-radio-group v-model="radio1">
                    <el-radio :label="true" size="large">更改密码</el-radio>
                    <el-radio :label="false" size="large">不更改密码</el-radio>
                  </el-radio-group>
                </div>
                <el-form-item label="旧密码" prop="currentPassword" v-if="radio1">
                  <el-input v-model="currentPassword" type="password" placeholder="请输入当前密码"></el-input>
                </el-form-item>
                <el-form-item label="新密码" prop="newPassword" v-if="radio1">
                  <el-input v-model="newPassword" type="password" placeholder="密码长度6-20位"></el-input>
                </el-form-item>
                <el-button type="primary" @click="saveChanges">保存更改</el-button>
              </el-form>
            </el-card>
          </el-col>
        </el-row>
      </el-tab-pane>

      <el-tab-pane label="员工信息" name="employeeInfo">
        <el-row justify="center" :gutter="20">
          <el-col :span="16">
            <el-card class="content-card" shadow="always">
              <h2 style="margin-top: 0">员工信息</h2>
              <el-form :model="employeeInfo" label-width="100px" :disabled="true">
                <el-form-item label="姓名">
                  <el-input v-model="employeeInfo.fullName"></el-input>
                </el-form-item>
                <el-form-item label="部门">
                  <el-input v-model="employeeInfo.departmentName"></el-input>
                </el-form-item>
                <el-form-item label="职位">
                  <el-input v-model="employeeInfo.positionName"></el-input>
                </el-form-item>
                <el-form-item label="基本工资">
                  <el-input v-model="employeeInfo.baseSalary"></el-input>
                </el-form-item>
                <el-form-item label="绩效工资">
                  <el-input v-model="employeeInfo.bonusSalary"></el-input>
                </el-form-item>
                <el-form-item label="雇佣状态">
                  <el-input v-model="employeeInfo.employmentStatus"></el-input>
                </el-form-item>
                <el-form-item label="入职日期">
                  <el-input :value="formatDate2(employeeInfo.hireDate)"></el-input>
                </el-form-item>
                <el-form-item label="离职日期">
                  <el-input :value="formatDate2(employeeInfo.reginationDate)"></el-input>
                </el-form-item>
              </el-form>
            </el-card>
          </el-col>
        </el-row>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'

// 从sessionStorage中获取当前登录用户的信息
const userInfo = ref({})
const currentPassword = ref('')
const newPassword = ref('')
const employeeInfo = ref({})
const currentuser = JSON.parse(sessionStorage.getItem('userInfo'))
const radio1 = ref(false)
const userForm = ref(null)
const userRules = ref({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
  ],
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
  ]
})
const activeTab = ref('userInfo')  // 当前激活的标签页

function fetchUserInfo() {
  if (currentuser) {
    axios.get(`http://localhost:8080/users/${currentuser.id}`)
        .then(response => {
          userInfo.value = response.data
        })
        .catch(error => {
          ElMessage.error('获取用户信息失败')
        })
  }
}

// 日期格式化
const formatDate = (date) => {
  if (!date) return '';
  const d = new Date(date);
  const year = d.getFullYear();
  const month = String(d.getMonth() + 1).padStart(2, '0'); // 月份补零
  const day = String(d.getDate()).padStart(2, '0'); // 日期补零
  const hours = String(d.getHours()).padStart(2, '0'); // 小时补零
  const minutes = String(d.getMinutes()).padStart(2, '0'); // 分钟补零
  const seconds = String(d.getSeconds()).padStart(2, '0'); // 秒补零

  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};

// 日期格式化2
const formatDate2 = (date) => {
  if (!date) return '';
  const d = new Date(date);
  const year = d.getFullYear();
  const month = String(d.getMonth() + 1).padStart(2, '0'); // 月份补零
  const day = String(d.getDate()).padStart(2, '0'); // 日期补零

  return `${year}-${month}-${day}`;
};

function fetchEmployeeInfo() {
  if (userInfo.value) {
    axios.get(`http://localhost:8080/employee/${currentuser.employeeId}`)
        .then(response => {
          employeeInfo.value = response.data
        })
        .catch(error => {
          ElMessage.error('获取员工信息失败')
        })
  }
}

function saveChanges() {
  userForm.value.validate((valid) => {
    if (valid) {
      if (radio1.value) {
        if (!currentPassword.value || !newPassword.value) {
          ElMessage.error('请输入当前密码和新密码')
          return
        }
        if (newPassword.value.length < 6 || newPassword.value.length > 20) {
          ElMessage.error('密码长度必须为6-20位之间')
          return
        }
        if (newPassword.value === currentPassword.value) {
          ElMessage.error('新密码不能与旧密码相同')
          return
        }
        axios.post('http://localhost:8080/users/verify-password', null, {
          params: {
            id: userInfo.value.id,
            oldPassword: currentPassword.value,
          }
        }).then((res) => {
          if (res.data === true) {
            // 验证通过，更新用户信息
            const updatedUserInfo = {
              userInfo: {
                username: userInfo.value.username,
                email: userInfo.value.email
              },
              newPassword: newPassword.value
            }
            axios.put(`http://localhost:8080/users/update/${userInfo.value.id}`, updatedUserInfo)
                .then((res) => {
                  ElMessage.success(res.data.message)
                  currentPassword.value = ''
                  newPassword.value = ''
                })
                .catch(error => {
                  ElMessage.error('信息更新失败')
                })
          } else {
            ElMessage.error('当前密码不正确');
          }
        }).catch(() => {
          ElMessage.error('服务器错误')
        })
      } else {
        const updatedUserInfo = {
          userInfo: {
            username: userInfo.value.username,
            email: userInfo.value.email
          },
          newPassword: null
        }
        axios.put(`http://localhost:8080/users/update/${userInfo.value.id}`, updatedUserInfo)
            .then((res) => {
              ElMessage.success(res.data.message)
              currentPassword.value = ''
              newPassword.value = ''
            })
            .catch(error => {
              ElMessage.error('信息更新失败')
            })
      }
    } else {
      ElMessage.error('请检查输入内容');
      return false;
    }
  });
}

onMounted(() => {
  fetchUserInfo()
  fetchEmployeeInfo()
})
</script>

<style scoped>
.container {
  padding: 30px 0;
}

.content-card {
  padding: 20px;
  background-color: white;
  border-radius: 10px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.el-tabs {
  margin-bottom: 20px;
}

h2 {
  margin-bottom: 20px;
  text-align: center;
}
</style>
